var express = require('express')
var app = express()

const formidable = require ('formidable'); // 用来处理 post


const DAO = require('./config')
const dao = new DAO('mongodb://localhost:27017/', 'test', 'user')

//添加数据
app.post('/add', (req, res) => { 
    let form = new formidable.IncomingForm()
    form.parse(req, (err, fields, files) => {
        let obj = { name: fields.name, age: fields.age, time: new Date() }
        dao.insert(obj).then(result => {
            res.send('插入成功')
            console.log(result)
        })
    })
})


//删除数据
app.post('/del', (req, res) => { 
    let form = new formidable.IncomingForm()
    form.parse(req, (err, fields, files) => {
        let obj = { name: fields.name }
        dao.del(obj).then(result => {
            res.send('删除成功')
        })
    })
})

//删除多条
app.post('/delAll', (req, res) => { 
    let form = new formidable.IncomingForm()
    form.parse(req, (err, fields, files) => {
        let obj = { age: fields.age }
        dao.del(obj,true).then(result => {
            res.send('删除成功')
        })
    })
})



// 修改数据
app.post ('/update', (req, res) => { 
    let form = new formidable.IncomingForm ()
    form.parse (req, (err, fields, files) => {
        let filter = { name: fields.filterName }
        let update = { name: fields.name }
        dao.update (filter, update).then (result => {
        res.send (' 修改成功 ')
        })
    })
})

// 查询数据
app.get('/init', (req, res) => { 
    if (req.query.age) { //前端有传来特定查询条件
        let age = { age: req.query.age }
        dao.query(age).then(restlt => {
            res.send({ restlt })
        })
    } else { //查询全部
        dao.query().then(restlt => {
            res.send({ restlt })
        })
    }
})






app.listen(4000,function(){
    console.log("服务器访问在4000端口上")
})